package com.ewili.x.special.task.thread.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ewili.framework.utils.ExceptionUtils;
import com.ewili.framework.utils.StringUtils;
import com.ewili.x.special.task.thread.inter.ValueThreadDaoTask;
import com.ewili.x.special.task.thread.inter.ValueThreadTask;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @author wonder
 */
@Slf4j
@Component
public class ValueThreadTaskImpl implements ValueThreadTask {

    @Autowired
    private ValueThreadDaoTask valueThreadDaoTask;

    @Override
    public void spideValue(String url, String code) {
        try {
            this.spide(url, code);
        } catch (Exception e) {
            log.error("url:{}", url, e);
        }

    }

    @Override
    public void spideValueStock(String url, String code) {

    }

    @Override
    public void spideValueStockProbablity(String urlProbablity) {

        Connection connection = Jsoup.connect(urlProbablity).timeout(30000000);
        connection.maxBodySize(0);

        String content = null;
        try {
            content = connection.get().body().text();
        } catch (IOException e) {
            ExceptionUtils.propagate(e);
        }

        JSONObject jsonObject = JSON.parseObject(content);
        valueThreadDaoTask.saveValueStockProbablity(jsonObject);
    }

    private void spide(String url, String code) {
        Connection connection = Jsoup.connect(url).timeout(30000000);
        connection.maxBodySize(0);

        String content = null;
        try {
            content = connection.get().body().text();
        } catch (IOException e) {
            ExceptionUtils.propagate(e);
        }

        if (content.contains("pages:0")) {
            return;
        }
        String subContent = StringUtils.substring(content, "data:[{", ",font:").replace("data:", "");
        JSONArray jsonArray = JSON.parseArray(subContent);
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject object = jsonArray.getJSONObject(i);
            valueThreadDaoTask.saveData(object, code);
        }
    }
}
